package com.love.rongcommon.base.controller;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONUtil;
import com.love.rongcommon.constant.AppKey;
import com.love.rongcommon.constant.enums.CommonEnum;
import com.love.rongcommon.jwt.JwtUtil;
import com.love.rongcommon.vo.AccessTokenVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

public class BaseController {

    @Resource(name = "stringRedisTemplate_0")
    private StringRedisTemplate stringRedisTemplate;

    protected AccessTokenVo getCurrentUserInfo() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String accessToken = request.getHeader(AppKey.ACCESS_TOKEN_KEY);
        CommonEnum.TOKEN_NOT_EXISTS.isNotEmpty(accessToken);

        // accessToken解密
        AccessTokenVo accessTokenVo = JwtUtil.decode(accessToken);

        String key = StrFormatter.format("{}:{}", AppKey.ACCESS_TOKEN_KEY, accessTokenVo.getUserId());
        String value = stringRedisTemplate.opsForValue().get(key);
        CommonEnum.TOKEN_NOT_EXISTS.isNotEmpty(value);

        // 格式化
        return JSONUtil.toBean(value, AccessTokenVo.class);
    }

    protected Long getCurrentUserId() {
        AccessTokenVo tokenDTO = this.getCurrentUserInfo();
        CommonEnum.TOKEN_NOT_EXISTS.isNotEmpty(tokenDTO);
        return tokenDTO.getUserId();
    }
}
